import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/employee_list.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/res/dimens.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:flutter_deer/widgets/dialog/input_dialog.dart';
import 'package:get/get.dart';

import 'dialog/bottom_integral_discount.dart';
import 'dialog/coupon_dialog.dart';
import 'dialog/selectable_list_dialog.dart';

class CashierPageDiscount extends StatefulWidget {
  const CashierPageDiscount({super.key});

  @override
  State<CashierPageDiscount> createState() => _CashierPageDiscountState();
}

class _CashierPageDiscountState extends State<CashierPageDiscount> {
  CashierPageProvider mProvider = Get.find<CashierPageProvider>();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        // 获取当班员工列表
        mProvider.getEmployeeList(success: (m) {
          // 获取员工配置
          mProvider.getEmployeeConfig(success: (isSuccess) {
            if (isSuccess) {
              // 获取当班员工列表
              mProvider.getEmployeeSelectList(success: (list) {
                if (!list.isNotEmpty) {
                  _initEmployeePerformance();
                }
              });
            }
          });
        });
      }
    });
  }

  // 初始化员工绩效
  void _initEmployeePerformance() {
    // 多选列表对话框
    showDialog<void>(
      context: context,
      builder: (context) => SelectableListDialog<EmployeeEntity>(
        title: '选择当班员工',
        items: mProvider.mAllListEmployee,
        selectionMode: SelectionMode.multiple,
        selectedItems: mProvider.mSelectListEmployee,
        itemBuilder: (employee) => employee.userName,
        itemCompare: (a, b) => a.userId == b.userId,
        onConfirmed: (selectedItems) {
          // mProvider.mSelectEmployee.value = mProvider.mSelectListEmployee.firstWhere((element) => element.userName == selectedItems.first);
          print('selectedItems:$selectedItems');
          mProvider.saveSelectEmployeeList(selectedItems, success: () {
            Navigator.of(context).pop();
          });
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final column = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标题
        Container(
          width: double.infinity,
          decoration: const BoxDecoration(
            color: Colours.dark_app_main,
            borderRadius: BorderRadius.only(topLeft: Radius.circular(3), topRight: Radius.circular(3)),
          ),
          padding: const EdgeInsets.only(left: 10.0, bottom: 8.0, top: 8, right: 1.0),
          child: const Text(
            '支付、优惠信息',
            style: TextStyle(fontSize: Dimens.font_sp16, color: Colours.white),
            textAlign: TextAlign.start,
          ),
        ),

        // 优惠区域
        Obx(() => Padding(
              padding: const EdgeInsets.symmetric(horizontal: 11.0),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    // 总金额行
                    _buildAmountRow('订单总金额：', '￥${mProvider.totalOrderAmountRx}'),

                    // 活动优惠
                    _buildDiscountRow(
                      '活动优惠：',
                      mProvider.mDiscountTotalTextRx,
                    ),
                    // 活动列表 - 可展开部分
                    _buildExpandableSection(context),

                    // 商户优惠券行
                    _buildCouponRow('商户优惠券：'),

                    // 积分抵现行
                    _buildIntegralRow(context),

                    // 线下优惠行
                    _buildOfflineRow(context),

                    // 员工绩效行
                    _buildEmployeeRow(context),

                    // 优惠总计行
                    _buildTotalDiscountRow(context),
                  ],
                ),
              ),
            )),
      ],
    );
    return column;
  }

  // 构建金额行
  Widget _buildAmountRow(String label, String value) {
    return _buildInfoRow(
      label,
      value,
      labelStyle: const TextStyle(fontSize: Dimens.font_sp14, color: Colours.text),
      valueStyle: const TextStyle(fontSize: Dimens.font_sp14, color: Colours.blue4B7EFE),
      onTap: () => {},
    );
  }

  // 构建优惠行
  Widget _buildDiscountRow(String label, String value) {
    // if (mProvider.mLiveDataDiscountRx?.discounts?.isEmpty == true) {
    //   return const SizedBox.shrink();
    // }
    return _buildInfoRow(
      label,
      value,
      valueStyle: const TextStyle(fontSize: Dimens.font_sp14, color: Color(0xFF13345F)),
      trailing: Icon(mProvider.isExpanded.value ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_right, size: 16.0, color: Colors.grey[400]),
      onTap: () {
        mProvider.isExpanded.value = !mProvider.isExpanded.value;
      },
    );
  }

  // 构建可展开部分 - 使用AnimatedContainer替代AnimatedSize
  Widget _buildExpandableSection(BuildContext context) {
    if (mProvider.getCurrentDiscount?.discounts.isNotEmpty != true) {
      return const SizedBox.shrink();
    }

    return AnimatedContainer(
      duration: const Duration(milliseconds: 400),
      curve: Curves.easeInOut,
      height: mProvider.isExpanded.value ? null : 0.0,
      constraints: BoxConstraints(
        maxHeight: mProvider.isExpanded.value ? _calculateExpandableHeight(context) : 0.0, // 设置最大高度限制
      ),
      child: SingleChildScrollView(
        physics: const NeverScrollableScrollPhysics(), // 禁用内部滚动
        child: Container(
          padding: const EdgeInsets.only(left: 8.0, right: 16.0, top: 0.0, bottom: 0.0),
          // color: Colors.red,
          child: ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: mProvider.getCurrentDiscount?.discounts?.length ?? 0,
            itemBuilder: (context, index) {
              final item = mProvider.getCurrentDiscount?.discounts?[index];
              return Padding(
                padding: const EdgeInsets.only(top: 4.0, bottom: 4.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(item?.discountTypeName ?? '', style: TextStyle(fontSize: Dimens.font_sp14, color: Colors.grey[700])),
                    Text('￥${item?.discountAmount}', style: TextStyle(fontSize: Dimens.font_sp14, color: Theme.of(context).primaryColor)),
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  // 计算可展开部分的高度
  double _calculateExpandableHeight(BuildContext context) {
    if (mProvider.getCurrentDiscount?.discounts?.isNotEmpty != true) {
      return 0.0;
    }

    const itemHeight = 48.0; // 每个 item 高度（含 padding）
    const headerPadding = 8.0;
    const dividerSpace = 16.0;

    return headerPadding + (mProvider.getCurrentDiscount?.discounts?.length ?? 0 * itemHeight) + dividerSpace;
  }

  // 构建商户优惠券行
  Widget _buildCouponRow(String label) {
    final couponText = mProvider.getCouponText();
    return _buildInfoRow(
      label,
      couponText.key,
      valueStyle: TextStyle(fontSize: Dimens.font_sp14, color: couponText.value),
      trailing: Icon(Icons.keyboard_arrow_right, size: 16.0, color: Colors.grey[400]),
      onTap: () {
        mProvider.getMemberCouponCount(success: () {
          showCouponDialog(context);
        });
      },
    );
  }

  // 构建积分抵现行
  Widget _buildIntegralRow(BuildContext context) {
    final mLiveDataDiscountRx = mProvider.getCurrentDiscount;
    if (mLiveDataDiscountRx?.integralToCashDiscount == null) {
      return const SizedBox.shrink();
    }

    final integralDiscountText = mProvider.getIntegralDiscountText();
    return _buildInfoRow(
      "积分抵现：",
      integralDiscountText.key,
      valueStyle: TextStyle(fontSize: Dimens.font_sp14, color: integralDiscountText.value),
      trailing: mLiveDataDiscountRx?.available == true ? Icon(Icons.keyboard_arrow_right, size: 16.0, color: Colors.grey) : SizedBox.shrink(),
      onTap: () {
        showDialog<void>(
          context: context,
          builder: (context) => BottomIntegralDiscount(
            onCancel: () {
              mProvider.getCurrentDiscount?.integralToCashDiscount?.useIntegral = '';
              mProvider.refreshDiscount(successCallback: (list) {
                Navigator.pop(context);
              });
            },
            onConfirm: (integral) {
              print('object $integral');
              mProvider.getCurrentDiscount?.integralToCashDiscount?.useIntegral = integral;
              mProvider.refreshDiscount(successCallback: (list) {
                Navigator.pop(context);
              });
            },
            myIntegral: '${mLiveDataDiscountRx?.integralToCashDiscount?.memberIntegral}',
            integralTips:
                '该订单积分最多抵扣${mLiveDataDiscountRx?.integralToCashDiscount?.maxAmount}元，每${mLiveDataDiscountRx?.integralToCashDiscount?.integralValue}积分=${mLiveDataDiscountRx?.integralToCashDiscount?.cashValue}元',
            maxDiscount: '${mLiveDataDiscountRx?.integralToCashDiscount?.maxUseIntegral}',
            useDiscount: '${mLiveDataDiscountRx?.integralToCashDiscount?.useIntegralAmount}',
            integralPrice: '${mLiveDataDiscountRx?.integralToCashDiscount?.cashValue}',
          ),
        );
      },
    );
  }

  // 构建线下优惠行
  Widget _buildOfflineRow(BuildContext context) {
    if (mProvider.offLineSwitch != 1) {
      return const SizedBox.shrink();
    }

    return Visibility(
      visible: mProvider.offLineSwitch == 1,
      child: _buildInfoRow(
        '线下优惠：',
        mProvider.offLineDiscount == 0.0 ? '未使用' : '${mProvider.offLineDiscount}',
        valueStyle: const TextStyle(fontSize: Dimens.font_sp14, color: Color(0xFF13345F)),
        trailing: Icon(Icons.keyboard_arrow_right, size: 16.0, color: Colors.grey[400]),
        onTap: () {
          if (!mProvider.canClickPayType()) {
            return;
          }
          showDialog<void>(
            context: context,
            builder: (context) => InputDialog(
              title: '输入线下优惠',
              inputType: InputType.double,
              maxValue: double.parse(mProvider.getMaxOffLineDiscount()),
              initialValue: '',
              onConfirm: (value) {
                mProvider.offLineDiscount.value = double.parse(value);
                // 处理输入的小数
              },
            ),
          );
        },
      ),
    );
  }

  // 构建优惠总计行
  Widget _buildTotalDiscountRow(BuildContext context) {
    final totalDiscount = mProvider.getFinalAmount();

    return _buildInfoRow(
      '应付金额：',
      '￥$totalDiscount',
      valueStyle: const TextStyle(fontSize: Dimens.font_sp14, color: Colours.green, fontWeight: FontWeight.bold),
      onTap: () {},
    );
  }

  // 构建员工绩效行
  Widget _buildEmployeeRow(BuildContext context) {
    if (!mProvider.employeeConfigOilRx.value) {
      return const SizedBox.shrink();
    }

    return _buildInfoRow(
      '服务人员：',
      mProvider.mSelectEmployee.value?.userName ?? '',
      valueStyle: const TextStyle(fontSize: Dimens.font_sp14, color: Color(0xFF4B7EFE)),
      trailing: Icon(Icons.keyboard_arrow_right, size: 16.0, color: Colors.grey[400]),
      onTap: () {
        // 多选列表对话框
        showDialog<void>(
          context: context,
          builder: (context) => SelectableListDialog<EmployeeEntity?>(
            title: '选择员工',
            items: mProvider.mSelectListEmployee,
            selectionMode: SelectionMode.single,
            selectedItems: [mProvider.mSelectEmployee.value],
            itemBuilder: (employee) => '${employee?.userName}',
            // 显示员工姓名
            itemCompare: (a, b) => a?.userId == b?.userId,
            onConfirmed: (selectedItems) {
              mProvider.mSelectEmployee.value = selectedItems.isNotEmpty ? selectedItems.first as EmployeeEntity : null;
              Navigator.of(context).pop();
            },
          ),
        );
      },
      onLongPress: () {
        // 处理长按事件
        _initEmployeePerformance();
      },
    );
  }

  // 通用信息行构建方法
  Widget _buildInfoRow(
    String label,
    String value, {
    TextStyle? labelStyle,
    TextStyle? valueStyle,
    Widget? trailing,
    required VoidCallback onTap,
    VoidCallback? onLongPress, // 新增长按回调参数
  }) {
    return InkWell(
      onTap: onTap,
      onLongPress: onLongPress, // 添加长按事件
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 7.0),
        decoration: const BoxDecoration(
          border: Border(bottom: BorderSide(color: Colours.dark_line, width: 0.1)),
        ),
        child: Row(
          children: [
            Text(label, style: labelStyle ?? TextStyle(fontSize: Dimens.font_sp14, color: Colors.black)),
            const Spacer(),
            Text(value, style: valueStyle ?? TextStyle(fontSize: Dimens.font_sp14, color: Colours.blue4B7EFE)),
            trailing ??
                SizedBox(
                  width: 16.0,
                  height: 16.0,
                  child: Opacity(
                    opacity: 0.0,
                    child: Icon(Icons.keyboard_arrow_right, size: 16.0, color: Colors.grey[400]),
                  ),
                )
          ],
        ),
      ),
    );
  }
}
